﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace MS.InformationManagement.BLL.GenericListDisplayer
{
    public class GenericListDisplayerBLL
    {
        /// <summary>
        /// Fetches the items from the list's default view.
        /// </summary>
        /// <param name="url">The list or document library's URL.</param>
        /// <param name="pageIndex">The page index to start fetchin the items from</param>
        /// <param name="pageSize">The total number of records to fetch per page.</param>
        /// <returns></returns>
        public static SPListItemCollection FetchItems(string url, int pageIndex, int pageSize)
        {
            SPListItemCollection foundItems = null;
            SPList targetList = SPContext.Current.Web.GetList(url);
            if (targetList != null)
            {
                foundItems = targetList.GetItems(targetList.DefaultView);
            }
            return foundItems;
        }

        /// <summary>
        /// Gets default edit form url from a given list or document library.
        /// </summary>
        /// <param name="url">The list or document library's URL.</param>
        /// <returns></returns>
        public static string GetEditFormUrl(string url)
        {
            string editUrl = string.Empty;
            SPList targetList = SPContext.Current.Web.GetList(url);
            if (targetList != null) { editUrl = targetList.DefaultEditFormUrl; }
            return editUrl;
        }

        /// <summary>
        /// Gets the column headers from a list or a document library's default view.
        /// </summary>
        /// <param name="url">The list or document library's URL.</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetColumnHeaders(string url)
        {
            Dictionary<string, string> foundColumns = null;
            SPList targetList = SPContext.Current.Web.GetList(url);
            if (targetList != null)
            {
                SPView defaultView = targetList.DefaultView;
                SPViewFieldCollection viewFields = defaultView.ViewFields;
                SPFieldCollection listFields = targetList.Fields;
                foreach (string currentFieldInternalName in viewFields)
                {
                    SPField currentField = (from SPField field in listFields
                                            where field.InternalName.Equals(currentFieldInternalName)
                                            select field).SingleOrDefault();
                    if (currentField != null)
                    {
                        foundColumns.Add(currentField.Title, currentField.InternalName);
                    }
                }
            }
            return foundColumns;
        }
    }
}
